package admin

import (
	"fmt"
	"go-amis-admin/amis"
	"slices"
	"strings"
)

type RoleModule struct {
	CrudModule[Role]
}

func NewRoleModule(basePath string) *RoleModule {
	module := &RoleModule{
		CrudModule: NewCrudModule(
			"角色权限",
			"role",
			"fa fa-key",
			basePath,
			200,
			Role{}, nil, nil, nil),
	}
	module.ColActions = slices.Insert(module.ColActions, 0, amis.Obj{
		"type":       "button",
		"tooltip":    "权限",
		"icon":       "fa fa-key",
		"actionType": "drawer",
		"drawer": amis.Obj{
			"title":    "权限设置",
			"position": "right",
			"size":     "lg",
			"body":     module.GetTreeSchema(),
		},
	})
	module.UpdatePage()
	return module
}

func (r *RoleModule) GetOptionsApi(ctx *AdminContext) {
	roles := make([]Role, 0)
	Instance.DB.Find(&roles)
	options := make([]amis.Obj, 0)
	for _, role := range roles {
		options = append(options, amis.Obj{
			"label": role.Label,
			"value": role.ID,
		})
	}
	ctx.Sucess(options, "")

}

func (r *RoleModule) SaveForRoleApi(ctx *AdminContext) {
	var data struct {
		RoleId   uint   `json:"roleId"`
		PermTree string `json:"permTree"`
	}
	if err := ctx.ShouldBindJSON(&data); err != nil {
		ctx.Fail(err.Error())
		return
	}
	Instance.Auth.DeletePermissionsForUser(fmt.Sprintf("%d", data.RoleId))
	perms := strings.Split(data.PermTree, ",")
	for _, perm := range perms {
		arr := strings.Split(perm, ".")
		Instance.Auth.AddPermissionsForUser(fmt.Sprintf("%d", data.RoleId), arr)
	}

	ctx.Sucess(nil, "保存成功")
}

func (r *RoleModule) GetPermsApi(ctx *AdminContext) {
	id := ctx.Query("id")
	perms, _ := Instance.Auth.GetPermissionsForUser(id)
	values := make([]string, 0)
	for _, perm := range perms {
		if len(perm) < 3 {
			values = append(values, perm[1])
		} else {
			values = append(values, perm[1]+"."+perm[2])
		}

	}
	ctx.Sucess(amis.Options{"permTree": strings.Join(values, ",")}, "")
}

func (r *RoleModule) GetTreeSchema() amis.Obj {
	items := make([]amis.Obj, 0)
	for _, site := range Instance.Sites {
		items = append(items, amis.Obj{
			"label": site.Label,
			"value": site.Name,
		})
	}
	tab := amis.New("select").
		Set("name", "site").
		Set("options", items).
		Set("label", "站点").Set("value", items[0]["value"])
	treeView := amis.New("input-tree").
		Set("name", "permTree").
		Set("multiple", true).
		Set("heightAuto", true).
		Set("valueField", "name").
		Set("onlyChildren", true).
		Set("source", "/admin/permList").
		Set("values", "${values}").Set("label", "资源")
	form := amis.New("form").
		Set("initApi", "/admin/role/getPerms?id=${ID}").
		Set("api", "/admin/role/saveForRole").
		Set("body", []amis.Obj{
			tab,
			treeView,
			amis.New("hidden").
				Set("value", "${ID}").
				Set("name", "roleId")})
	return form
}
